<template>
  <el-container style="height: 1000px; border: 1px solid #eee">
    <el-main>
      <router-view/>
      <el-container style="height: 900px">
        <el-aside style="height:750px; border:1px solid #eee; background-color: #f6f6f6">
          <el-row>
            <div style="width: 100%;height: 120px;align-content: center;padding-top: 20px">
              <el-avatar :src="'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'" :size="100"
              ></el-avatar>
            </div>
            <div style="width: 100%;height: 30px;align-content: center;">
              <p class="name">{{userName}}</p>
            </div>
          </el-row>
          <el-row style="height:100px"/>
          <el-row>
            <div style="width: 100%;align-content: center;padding-bottom: 20px">
              <p style="font-family: 'Microsoft YaHei',sans-serif;color: gray;font-size: 12px;font-weight: lighter;">综合评分</p>
              <el-rate v-model="star"
                       disabled
                       show-score
                       text-color="#ff9900"
                       score-template="{value}"></el-rate>
            </div>
          </el-row>
          <el-row>
            <div style="width:100%; background-color: #2c3e50; color: #ffffee; border:0">
              <p class="title2">咨询状态</p>
              <p class="digit2">{{consultStatus}}</p>
            </div>
          </el-row>
          <el-menu background-color="#2c3e50" text-color="#ffffee"  style="height: 170px">
            <el-menu-item index="1" @click="stopEvent(chatName)">
              <template #title>中止咨询</template>
            </el-menu-item>
            <el-menu-item index="2" @click="Helpevent();" v-if="mentor===''">
              <template #title>求助督导</template>
            </el-menu-item>
            <el-menu-item index="2" @click="backToMentor()" v-if="mentor!==''&&msgsynchro===true">
              <template #title>回到督导</template>
            </el-menu-item>
            <el-menu-item index="3" @click="SendSynchro()" v-if="synchro===true && msgsynchro===false">
              <template #title>同步消息</template>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-container>
          <el-header height="60px" style="text-align: left;background-color: #f6f6f6;padding-left: 30px">
            <p class="title1">
              <el-dropdown>
              <i class="el-icon-setting"></i>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="this.chatName='61';this.mList=[];
                    this.nextReqMessageID='';this.isCompleted=false;getMess(15,chatName,'')">61</el-dropdown-item>
                  <el-dropdown-item @click="this.chatName='qwx124';this.chatNick='qwx124' ;this.mList=[];
                    this.nextReqMessageID='';this.isCompleted=false;getMess(15,chatName,'')">qwx124</el-dropdown-item>
                  <el-dropdown-item @click="this.chatName='1';this.mList=[];
                    this.nextReqMessageID='';this.isCompleted=false;getMess(15,chatName,'')">1</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>{{'访客'+chatName}}</p>
          </el-header>
          <el-main>
            <span style="width: 150px"><el-button type="text" @click="getMoreMess(chatName)">查看更多</el-button></span>
            <el-table id="eltable" :show-header="false" :data="mList" :height="450">
              <el-table-column prop="message" align="left" >
                <template #default="scope" >
                  <span style="font-size: 12px;color:gray;font-weight: lighter" v-if="scope.row.message!==''">  {{scope.row.time}}</span>
                  <el-row>
                    <el-avatar :src="'http://img.meituan.net/avatar/8e121229f5fbde1040d0969a095afdbf49867.jpg'" v-if="scope.row.message!==''"></el-avatar>
                    &nbsp; &nbsp;
                    <el-card class="box-class" style="max-width: 300px;--el-card-padding:10px;--el-card-border-radius: 12px;
                    background-color: rgba(21,157,255,0.4)" v-if="scope.row.message!=='' && scope.row.type === 'text'">
                      {{scope.row.message}}
                    </el-card>
                    <el-card class="box-class" style="max-width: 300px;--el-card-padding:10px;--el-card-border-radius: 12px;
                        background-color: rgba(21,157,255,0.4)" v-else-if="scope.row.message!==''  && scope.row.type === 'pic'">
                      <el-image :src="scope.row.message" @click="zoomout(scope.row.message)"></el-image>
                    </el-card>
                    <el-card class="box-class" style="max-width: 300px;--el-card-padding:10px;--el-card-border-radius: 12px;
                    background-color: rgba(21,157,255,0.4)" v-else-if="scope.row.message!=='' && scope.row.type === 'history'">
                      <el-button type="primary" @click="historyCheck(scope.row.message)">消息记录</el-button>
                    </el-card>
                    <el-card class="box-class" style="max-width: 300px;--el-card-padding:10px;--el-card-border-radius: 12px;
                    background-color: rgba(21,157,255,0.4)" v-else-if="scope.row.message!=='' && scope.row.type === 'sound'">
                      <div id="bdtts_div_id">
                        <audio id="tts_audio_id">
                          <source id="tts_source_id" src="" type="audio/mpeg">
                          <embed id="tts_embed_id" height="0" width="0" src="">
                        </audio>
                      </div>
                      <el-button type="primary" @click="voicePlay(scope.row.message)" round icon="el-icon-video-play">播放语音</el-button>
                    </el-card>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column prop="mine">
                <template #default="scope" style="float: right">
                  <el-row style="height:10px"><span v-if="false">abcd</span></el-row>
                  <el-row align="right" style="float: right">
                    <el-card class="box-class" style="max-width: 300px;--el-card-padding:10px;--el-card-border-radius: 12px;" v-if="scope.row.mine!==''  && scope.row.type === 'text'">
                      {{scope.row.mine}}
                    </el-card>
                    <el-card class="box-class" style="max-width: 300px;--el-card-padding:10px;--el-card-border-radius: 12px;" v-else-if="scope.row.mine!==''  && scope.row.type === 'pic'">
                      <el-image :src="scope.row.mine" @click="zoomout(scope.row.mine)"></el-image>
                    </el-card>
                    &nbsp; &nbsp;
                    <el-avatar :src="'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'" v-if="scope.row.mine!=='' "></el-avatar>
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
            <el-row>
              <textarea
                  placeholder="请输入消息内容，最多可输入200个字"
                  v-model="textarea"
                  maxlength="200"
                  @keydown="messageSendlisten"
                  style="width: 100%;height: 150px"
              ></textarea>
            </el-row>
<!--            <el-button @click="sendTry" type="primary">测试</el-button>-->
            <!-- consultRecordId直接赋值 仅用于测试 -->
<!--            <el-button @click="dialogVisible5 = true" type="primary">测试</el-button>-->

            <el-button @click="setButton" type="primary" style="float: right">发送</el-button>

            <el-button @click="handleSendImageClick" type="primary" plain icon="el-icon-picture-outline" style="float: right">图片</el-button>&nbsp;
<!--            <i class="el-icon-picture-outline" title="发图片" @click="handleSendImageClick" style="float: right;width:50px;height: 50px"></i>-->

            <input
                type="file"
                id="imagePicker"
                ref="imagePicker"
                accept=".jpg, .jpeg, .png, .gif, .bmp"
                @change="sendImage"
                style="display:none"
            />
            <!-- <div class="t_limit">当前还可发送{{200-(textarea.length)}}个字</div> -->
            <el-dialog
                title="请填写"
                v-model="dialogVisible"
                width="30%"
            >
              <el-form :model="form">
                <el-form-item label="姓名" :label-width="120">
                  <el-select v-model="form.mentor" @change="pickMentorName($event)" filterable placeholder="请选择">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="danger" @click="dialogVisible=false">取消</el-button>
                  <el-button type="primary" @click="HandleHelp(toMentor)">添加</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>
            <!-- 诊断 -->
            <el-dialog
                title="请填写"
                v-model="dialogVisible2"
                width="30%"
            >
              <el-form :model="commentForm">
                <el-form-item label="id" :label-width="120" disabled v-if="false">
                  <el-input v-model="consultRecordId" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item label="判断" :label-width="120">
                  <el-input v-model="commentForm.toDiagnosis" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item label="详情" :label-width="120">
                  <el-input v-model="commentForm.toComment" type="textarea" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="danger" @click="dialogVisible2=false;backtoMe()">取消</el-button>
                  <el-button type="primary" @click="HandleComment()">添加</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>
            <el-dialog
                title="图片预览"
                v-model="dialogVisible3"
                width="60%"
            >
              <el-image :src="imageZoom" :fit="'fit'"></el-image>
            </el-dialog>

            <el-dialog
                title="查看消息记录"
                v-model="dialogVisible4"
                width="30%"
            >
              <el-table id="eltable3" :show-header="false" :data="historyMessage" :height="450">
                <el-table-column prop="from" align="left" >
                  <template #default="scope" >
                    <el-row>
                      <el-avatar :src="'http://img.meituan.net/avatar/8e121229f5fbde1040d0969a095afdbf49867.jpg'" v-if="scope.row.from!==''"></el-avatar>
                      &nbsp; &nbsp;
                      <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;
                    background-color: rgba(21,157,255,0.4)" v-if="scope.row.from!==''">
                        {{scope.row.from}}
                      </el-card>
                      <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;
                        background-color: rgba(21,157,255,0.4)" v-else-if="scope.row.from!==''  && scope.row.type === 'pic'">
                        <el-image :src="scope.row.from" @click="zoomout(scope.row.from)"></el-image>
                      </el-card>
                    </el-row>
                  </template>
                </el-table-column>
                <el-table-column prop="consultant">
                  <template #default="scope" style="float: right">
                    <el-row align="right" style="float: right">
                      <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;" v-if="scope.row.to!==''">
                        {{scope.row.to}}
                      </el-card>
                      <el-card class="box-class" style="max-width: 150px;--el-card-padding:10px;--el-card-border-radius: 12px;" v-else-if="scope.row.to!==''  && scope.row.type === 'pic'">
                        <el-image :src="scope.row.to" @click="zoomout(scope.row.to)"></el-image>
                      </el-card>
                      &nbsp; &nbsp;
                      <el-avatar :src="'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'" v-if="scope.row.to!=='' "></el-avatar>
                    </el-row>
                  </template>
                </el-table-column>
              </el-table>
            </el-dialog>

            <!-- 测试 -->
            <el-dialog
                title="请填写"
                v-model="dialogVisible5"
                width="30%"
            >
              <el-form :model="commentForm">
                <el-form-item label="id" :label-width="120">
                  <el-input v-model="consultRecordId" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="danger" @click="dialogVisible5=false;backtoMe()">取消</el-button>
                  <el-button type="primary" @click="testRecord">添加</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>

          </el-main>
        </el-container>

      </el-container>


    </el-main>
  </el-container>
</template>

<script>
import tim from '../../tim'
import TIM from 'tim-js-sdk/tim-js-friendship.js'
const userUrl = 'http://img.meituan.net/avatar/8e121229f5fbde1040d0969a095afdbf49867.jpg'
const circleUrl = 'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'
function sleep(delay) {
  for(let t = Date.now(); Date.now() - t <= delay;);
}

const emojiMap = {         // 根据[呲牙]可匹配的路径地址
  '[emoji-_1]': 'emoji-_1.png',
  '[emoji-_2]': 'emoji-_2.png',
  '[emoji-_3]': 'emoji-_3.png'
}
const emojiUrl = 'https://psychology-w.oss-cn-shanghai.aliyuncs.com/test/'   // 为<img src="https://main.qcloudimg.com/raw/6be88c30a4552b5eb93d8eec243b6593.png"  style="margin:0;">图片的地址
function offTime (value) {
  var v = value;
  var date = new Date(v * 1000);
  var Y = date.getFullYear() + "-";
  var M =
      (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
  var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var h =
      (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var m =
      date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  let dt = new Date(Date.parse(new Date()));
  let current = dt.getFullYear() + "-" + dt.getMonth() + "-" + dt.getDate();
  let system = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
  if (current === system) {
    return h + m;
  } else {
    return M + D;
  }
}
export default {
  inject:['reload'],
  name: "ConsChat",
  data(){
    return{
      rawHtml:'',
      imageZoom:'',
      h:0,//定义时，分，秒，毫秒并初始化为0；
      m:0,
      s:0,
      ms:0,
      time:0, //定时器
      str:'00:00:00',
      times:0, //统计共多少分钟时间
      options: [
        {
          value: '1',
          label: 'mentor',
        },
        {
          value: '2',
          label: 'qwy',
        },
        {
          value: '3',
          label: 'qwz',
        },
        {
          value: '4',
          label: 'abc',
        },
        {
          value: '5',
          label: 'asd',
        },
      ],
      duration:0,
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible3:false,
      dialogVisible4:false,
      dialogVisible5:false,
      userId:'',
      userName:'',
      star:4.7,
      chatName: "", //查看的某个人name
      toUserId: "", //查看的某个人id
      avatar: "", //查看的某个人avatar
      lookup: "", //用户查找的名字
      isActive: "1",
      loading: false, //加载中
      textarea: "", //输入信息
      textarea2:"",
      rListOff: false,
      rRightOff: false,
      // emojiMap: emojiMap,
      // emojiUrl: emojiUrl,
      rList: [], //会话列表
      hList: [], //具体信息
      mList:[],
      mList2:[],
      helphelp:false,
      helpstop:false,
      mentor:'',
      visitor:'',
      consultStatus:"咨询中",
      nextReqMessageID:'',
      isCompleted:false,
      formVisible:false,
      consultRecordId:0,
      helpRecordId:0,
      uploadFile:'',
      chatNick:'',
      synchro:false,
      msgsynchro:false,
      form:{
        mentor:''
      },
      isToMentor:2,
      toMentor:{
        id:'',
        name:''
      },
      commentForm:{
        consultRecordId:0,
        toDiagnosis:'',
        toComment:''
      },
      historyMessage:[]
    }
  },
  methods: {
    voicePlay(src){
      let ttsDiv = document.getElementById('bdtts_div_id');
      let au1 = '<audio id="tts_autio_id" autoplay="autoplay">';
      let sss = '<source id="tts_source_id" src="'+ src +'" type="audio/mpeg">';
      let eee = '<embed id="tts_embed_id" height="0" width="0" src="">';
      let au2 = '</audio>';
      ttsDiv.innerHTML = au1 + sss + eee + au2;
      let ttsAudio = document.getElementById('tts_audio_id');
      ttsAudio.play();

    },
    testRecord(){ //consultRecordId的直接赋值，仅用于测试
      console.log(this.consultRecordId)
      this.commentForm.consultRecordId = this.consultRecordId
      console.log(this.commentForm.consultRecordId)
      this.dialogVisible5 = false
    },

    async SynchroEvent(){
      const _this = this
      console.log(_this.mentor)
      console.log(_this.mList2)
      for (let item of _this.mList2){
        let message = this.tim.createTextMessage({
          to: String(_this.mentor),
          conversationType: this.TIM.TYPES.CONV_C2C,
          payload: {
            text: item.message === ''?item.mine:item.message,
          },
          cloudCustomData:item.message===''?'consultant':'user'
        });
        await this.tim.sendMessage(message).then(_=>{
          console.log('success')
        })
      }
    },


    backToMentor(){
      this.$router.push({
        path:'/cons/mentorchat',
        query:{
          chatName: this.mentor,
          visitor: this.visitor,
          consultRecordId:this.consultRecordId,
          helpRecordId:this.helpRecordId
        }
      }).then(_=>{
        this.$router.go(0)
      })
    },
    zoomout(url){
      const _this = this
      _this.dialogVisible3 = true
      _this.imageZoom = url
    },
    backtoMe(){
      this.$router.push({
        path:'/cons/me'
      }).then(_=>{
        this.$router.go(0)
      })
    },
    async HandleComment(){
      const _this = this
      _this.commentForm.consultRecordId = _this.consultRecordId
      console.log(_this.commentForm)
      await _this.$axios.post('http://106.14.247.163:8080/consultant/commentConsult',_this.commentForm).then(resp=>{
        console.log(resp)
      })

      _this.dialogVisible2 = false;

      this.$router.push({
        path:'/cons/me'
      }).then(_=>{
        this.$router.go(0)
      })
    },
    pickMentorName(id){
      const _this = this
      let obj = {}

      obj = _this.options.find((item)=>{
        if(item.value === id){
          _this.toMentor.id = item.value
          _this.toMentor.name = item.label
        }
      })
    },
    start(){  //开始
      this.time=setInterval(this.timer,50);
    },

    stop(){  //暂停
      const _this = this
      if (parseInt(_this.helpRecordId)===0){
        let t = new Date()
        let start = new Date(window.localStorage.getItem('cons'+_this.chatName))
        let delta = t.getTime()-start.getTime()
        _this.duration = Math.floor(delta/(60*1000))
        console.log(_this.duration)
        clearInterval(this.time);
        _this.consultStatus = "已结束"
        window.localStorage.removeItem('cons'+_this.chatName)
      }else{
        _this.$message.error('请先结束与督导的对话再结束！')
      }

    },
    reset(){  //重置
      clearInterval(this.time);
      this.h=0;
      this.m=0;
      this.ms=0;
      this.s=0;
      this.str="00:00:00";
    },
    timer(){                //定义计时函数
      this.ms=this.ms+50;        //毫秒
      if(this.ms>=1000){
        this.ms=0;
        this.s=this.s+1;        //秒
      }
      if(this.s%4===0){
        this.consultStatus="咨询中"
      }else if (this.s%4===1){
        this.consultStatus = "咨询中."
      }else if (this.s%4===2){
        this.consultStatus = "咨询中.."
      }else {
        this.consultStatus = "咨询中..."
      }

    },
    toDub(n){  //补0操作
      if(n<10){
        return "0"+n;
      }
      else {
        return ""+n;
      }
    },
    async stopEvent(){
      this.stop()
      const _this = this
      console.log(_this.helphelp,_this.helpstop)
      if (parseInt(_this.helpRecordId)===0){
        console.log(_this.commentForm.consultRecordId)
        let cri = 0
        if(_this.$route.query.consultRecordId){
          cri = _this.$route.query.consultRecordId;
        }else if(_this.commentForm.consultRecordId!==0){
          cri = _this.commentForm.consultRecordId
        }else{
          cri = _this.consultRecordId
        }
        let message = this.tim.createTextMessage({
          to: _this.chatName,
          conversationType: this.TIM.TYPES.CONV_C2C,
          payload: {
            text: '--结束咨询--',
          },
          cloudCustomData:cri
        });
        await this.tim.sendMessage(message).then(function (imResponse) {
          console.log("success")
        }).catch(function (imError) {
          // 发送失败
          console.warn("sendMessage error:", imError);
        });

        await _this.$axios.post('http://106.14.247.163:8080/visitor/endConsult',
            {consultRecordId:_this.commentForm.consultRecordId,duration:Math.abs(Math.floor(Math.random()*10))})
            .then(
                resp=>{console.log(resp)
              })
            .catch(err=>{
              console.warn(err)
            })

        this.dialogVisible2 = true
      }
    },
    handleSendImageClick() {
      this.$refs.imagePicker.click()
    },
    handleSendImageClick2() {
      this.$refs.imagePicker2.click()
    },
    async sendImage() {
      const _this = this
      const message = this.tim.createImageMessage({
        to: _this.chatName,
        conversationType: this.TIM.TYPES.CONV_C2C,
        payload: {
          file: document.getElementById('imagePicker') // 或者用event.target
        },
        onProgress: function(event) { console.log('file uploading:', event) }
      })

      await this.tim
          .sendMessage(message)
          .then( () => {
            _this.mList.push({message: '', mine: message.payload.imageInfoArray[0].imageUrl, type: 'pic'})
            if (_this.msgsynchro === false) {
              _this.mList2.push({message: '', mine: '[图片]', type: 'text'})
            }
            else {
              const message2 = this.tim.createTextMessage({
                to: _this.mentor,
                conversationType: this.TIM.TYPES.CONV_C2C,
                payload: {
                  text: '[图片]' // 或者用event.target
                },
              })
              tim.sendMessage(message2)
            }
          })
          .catch(imError => {

          })
      this.below()
    },
    Helpevent(){
      const _this = this
      if (_this.helpstop){
        _this.$message.error('您已经进行过求助')
      }else{
        _this.helphelp = true
        _this.dialogVisible = true
      }
    },
    async HandleHelp(mentor){
      const self = this
      self.dialogVisible = false
      if (mentor.id===''||mentor.id===0||mentor.id===null||mentor.id===undefined){
        self.$message.warning('未选择督导，求助没有开始')
      }else{
        self.$message.success('已选择督导，求助开始')
        self.mentor = String(mentor.id)
        window.localStorage.setItem('mentor'+mentor.id,String(new Date()))
        self.$axios.post('http://106.14.247.163:8080/consultant/startHelp',
            {consultRecordId:self.commentForm.consultRecordId,fromId:window.sessionStorage.getItem('userid'),toId:mentor.id})
            .then(resp=>{
              self.helpRecordId = resp.data.data.helpRecordId
              console.log(self.helpRecordId)
            }).catch(err=>{
          console.warn(err)
        })
        let message = this.tim.createTextMessage({
          to: String(mentor.id),
          conversationType: this.TIM.TYPES.CONV_C2C,
          payload: {
            text: '求助',
          },
          cloudCustomData:'askhelp'
        });
        let promise = tim.sendMessage(message);
        promise
            .then(function (imResponse) {
              // 发送成功
              self.textarea = "";
              console.log("success")
              self.below();
            })
            .catch(function (imError) {
              // 发送失败
              console.warn("sendMessage error:", imError);
            });
        console.log(mentor.id)
        this.helphelp = true
        this.synchro = true

      }

    },
    async SendSynchro(){
      const self = this
      if (self.synchro === true){
        self.msgsynchro = true
      }

      await self.SynchroEvent()

      await self.$router.push({
        path: '/cons/mentorchat',
        query: {
          chatName: self.toMentor.id,
          visitor: self.chatName,
          helpRecordId: self.helpRecordId,
          consultRecordId:self.consultRecordId,
        }
      }).then(_=>{
        self.$router.go(0)
      })
    },
    handleAvatarSuccess(res, file) {
      const _this = this
      _this.uploadFile = URL.createObjectURL(file.raw)
    },

    //自动保持在最底部
    below() {
      this.$nextTick(() => {
        let container = this.$el.querySelector("#eltable .el-table__body-wrapper");
        container.scrollTop = container.scrollHeight;
      });
    },
    //回车发送文本 阻止浏览器默认换行操作
    messageSendlisten(event) {
      if (event.keyCode === 13) {
        this.setButton(); // 发送文本
        event.preventDefault(); // 阻止浏览器默认换行操作
        return false;
      }
    },
    //消息已读
    read(id) {
      let promise = this.tim.setMessageRead({ conversationID: id });
      promise
          .then(function (imResponse) {
            // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
          })
          .catch(function (imError) {
            // 已读上报失败
            console.warn("setMessageRead error:", imError);
          });
    },
    //临时
    // sendTry(){
    //   const self = this;
    //   let message = this.tim.createCustomMessage({
    //     to: self.chatName,
    //     conversationType: this.TIM.TYPES.CONV_C2C,
    //     payload: {
    //       data: JSON.stringify(  // stringify中放消息记录的内容，格式为{time:时间戳或yyyy-mm-dd,
    //           // from:咨询人,
    //           // to:咨询师,
    //           // avatar:当前说话人的头像,
    //           // type:消息类型，'text' 或 'pic'}，下方是举例
    //        [{time:'1001',from:'hello',to:'',avatar:circleUrl,type:'text'},
    //         {time:'1002',from:'',to:'hi',avatar:circleUrl,type:'text'},
    //         {time:'1003',from:'你好',to:'',avatar:circleUrl,type:'text'},
    //         {time:'1004',from:'',to:'再见',avatar:circleUrl,type:'text'}]
    //       )
    //     },
    //   });
    //   tim.sendMessage(message).then(imResponse=>{
    //     self.mList.push({message:'',mine:'消息记录',type:'text'})
    //     self.below()
    //   })
    // },

    historyCheck(history){
      const _this = this
      console.log(history)
      _this.historyMessage = JSON.parse(history)
      _this.dialogVisible4 = true
    },
    //发送消息
    setButton() {
      const self = this;
      if (self.textarea.split(" ").join("").length === 0)
        return this.$message({
          message: "请输入正确信息",
          type: "warning",
        });
      let message = this.tim.createTextMessage({
        to: self.chatName,
        conversationType: this.TIM.TYPES.CONV_C2C,
        payload: {
          text: self.textarea,
        },
        cloudCustomData:self.consultRecordId===0?'':self.consultRecordId
      });
      let promise = tim.sendMessage(message);
      promise
          .then(function (imResponse) {
            // 发送成功
            self.textarea = "";
            console.log("success")
            let cvtMessage = message.payload.text
            self.mList.push({message:'',mine:cvtMessage,type:'text'})
            self.mList2.push({message:'',mine:cvtMessage,type:'text'})
            self.below();
          })
          .catch(function (imError) {
            // 发送失败
            console.warn("sendMessage error:", imError);
          });
      console.log(message)

      // 发送消息
      if(self.msgsynchro === true){
        let message2 = this.tim.createTextMessage({
          to: self.mentor,
          conversationType:this.TIM.TYPES.CONV_C2C,
          payload:{
            text: message.payload.text
          },
          cloudCustomData:'consultant'
        })
        let promise2 = tim.sendMessage(message2)
        promise2
            .then(function (imResponse) {
              // 发送成功
              self.textarea = "";
              console.log("success")
              self.below();
            })
            .catch(function (imError) {
              // 发送失败
              console.warn("sendMessage error:", imError);
            });
      }
    },

    setImageUpload(file){
      const _this = this
      let message = tim.createImageMessage({
        to: _this.chatName,
        conversationType: TIM.TYPES.CONV_C2C,
        // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
        // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
        // priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
        payload: {
          file: file,
        },
        // 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到，v2.10.2起支持）
        // cloudCustomData: 'your cloud custom data'
        onProgress: function(event) { console.log('file uploading:', event) }
      });

      // 2. 发送消息
      let promise = tim.sendMessage(message);
      promise.then(function(imResponse) {
        // 发送成功
        console.log(imResponse);
      }).catch(function(imError) {
        // 发送失败
        console.warn('sendMessage error:', imError);
      });
    },

    getMess(count, chatName, nextSeq) {
      const _this = this
      let promise2 = tim.getMessageList({
        conversationID: 'C2C' + chatName,
        nextReqMessageID:nextSeq,
        count: 15,
      });
      promise2.then(function (imResponse) {
        let tempList=[]
        console.log(imResponse.data.messageList)
        for (const item of imResponse.data.messageList) {
          let time = offTime(item.time)
          let m = ''
          if (item.type === "TIMImageElem"){
            let m = item.payload.imageInfoArray[0].imageUrl
            if (item.from === chatName) {
              tempList.push({time:time,message: m, mine: '',type:'pic'})
            } else {
              tempList.push({time:time,message: '', mine: m,type:'pic'})
            }
          }else if(item.type === "TIMTextElem"){
            if (item.cloudCustomData === 'user') {
              continue
            } else if (item.cloudCustomData === 'consultant') {
              continue
            } else if (item.cloudCustomData === 'askhelp') {
              m = '----督导介入---- : '
            } else {
              m = item.payload.text
            }
            if (item.from === chatName) {
              tempList.push({time:time,message: m, mine: '',type:'text'})
            } else {
              tempList.push({time:time,message: '', mine: m,type:'text'})
            }
          }else if (item.type === 'TIMCustomElem'){
            if (item.from === chatName) {
              tempList.push({time:time,message: item.payload.data, mine: '',type:'history'})
            } else {
              tempList.push({time:time,message: '', mine: '[消息记录]',type:'text'})
            }
          }else{
            if (item.from === chatName) {
              tempList.push({time:time,message: item.payload.url, mine: '',type:'sound'})
            }
          }
        }
        tempList = tempList.concat(_this.mList)
        _this.mList = tempList
        _this.nextReqMessageID = imResponse.data.nextReqMessageID
        _this.isCompleted = imResponse.data.isCompleted
        console.log(imResponse)
      });
    },
    getMoreMess(chatName){
      const _this = this
      if (_this.isCompleted===false){
        _this.getMess(15,chatName,_this.nextReqMessageID)
      }
    },
    handleClose() {
      let promise = this.tim.logout();
      this.dialogVisible = false;
      promise
          .then(function (imResponse) {
            console.log(imResponse.data);
          })
          .catch(function (imError) {
            console.warn("logout error:", imError);
          });
    },
  },
  created(){
    const userId = window.sessionStorage.getItem('userid') // 这个是
    const userSig = window.sessionStorage.getItem('usersig')
    const _this = this
    _this.consultStatus = "咨询中"
    _this.userName = window.sessionStorage.getItem('name')
    _this.star = window.sessionStorage.getItem('grade')
    _this.chatName = _this.$route.query.chatName //从query上拿取信息，包括聊天名，督导，咨询Id，求助Id
    _this.mentor = _this.$route.query.mentor?_this.$route.query.mentor:''
    _this.commentForm.consultRecordId = _this.$route.query.consultRecordId?_this.$route.query.consultRecordId:0
    _this.consultRecordId = _this.$route.query.consultRecordId?_this.$route.query.consultRecordId:0
    _this.helpstop = _this.$route.query.helped?_this.$route.query.helped:false
    console.log(_this.consultRecordId)
    if (_this.mentor!==''){
      _this.synchro = true
      _this.msgsynchro = true
    }
    _this.visitor = _this.chatName
    _this.helpRecordId = _this.$route.query.helpRecordId?_this.$route.query.helpRecordId:0

    _this.start() //计时动画开始

    console.log(userId,userSig)

    _this.$axios.get('http://106.14.247.163:8080/consultant/getAvailableSupervisors/'+userId).then(resp=>{
      _this.options = []
      for (let item of resp.data.data){
        if (item.userInfo!==null){
          _this.options.push({value:item.userInfo.userId,label:item.userInfo.userName})
        }
      }
      console.log(_this.options)
    })
    let promise = tim.login({userID:userId,userSig:userSig})
    promise.then((imResponse)=>{
      console.log(imResponse.data);
    }).catch((imError)=>{
      console.warn(imError)
    })
    tim.on(TIM.EVENT.SDK_READY, function(event) {
      tim.getUserProfile({userIDList:[_this.chatName]}).then(imResponse=>{
        _this.chatNick = imResponse.data[0].nick
      })
      let promise2 = tim.getMessageList({
        conversationID: 'C2C' + _this.chatName,
        nextReqMessageID:'',
        count: 15,
      });
      promise2.then(function (imResponse) {
        let tempList=[]
        console.log(imResponse.data.messageList)
        for (const item of imResponse.data.messageList) {
          let m = ''
          let time = offTime(item.time)
          let cvtMessage = []
          if (item.type === "TIMImageElem"){
            let m = item.payload.imageInfoArray[0].imageUrl
            if (item.from === _this.chatName) {
              tempList.push({time:time,message: m, mine: '',type:'pic'})
            } else {
              tempList.push({time:time,message: '', mine: m,type:'pic'})
            }
          }
          else if(item.type === "TIMTextElem"){
            if (item.cloudCustomData === 'user') {
              continue
            } else if (item.cloudCustomData === 'consultant') {
              continue
            } else if (item.cloudCustomData === 'askhelp') {
              m = '----督导介入---- : '
            } else {
              m = item.payload.text
            }
            if (item.from === _this.chatName) {
              if (item.cloudCustomData!==''){
                _this.commentForm.consultRecordId = m!=='--结束咨询--'? parseInt(item.cloudCustomData):0
              }
              console.log(_this.commentForm.consultRecordId)
              tempList.push({time:time,message: m, mine: '',type:'text'})
            } else {
              tempList.push({time:time,message: '', mine: m,type:'text'})
            }
          }
          else if (item.type === 'TIMCustomElem'){
            if (item.from === _this.chatName) {
              tempList.push({time:time,message: item.payload.data, mine: '',type:'history'})
            } else {
              tempList.push({time:time,message: '', mine: '[消息记录]',type:'text'})
            }
          }
          else{
            if (item.from === _this.chatName) {
              tempList.push({time:time,message: item.payload.url, mine: '',type:'sound'})
            } else {
              tempList.push({time:time,message: '', mine: '[消息记录]',type:'text'})
            }
          }
        }
        tempList = tempList.concat(_this.mList)
        _this.mList = tempList
        _this.nextReqMessageID = imResponse.data.nextReqMessageID
        _this.isCompleted = imResponse.data.isCompleted
        _this.below()
        console.log(imResponse)
      });
    });


    let onMessageReceived = function(event) {
      let cvtMessage = ''
      let time = offTime(event.data[0].time)
      console.log(event.data[0])
      if (event.data[0].from === _this.chatName){
        _this.commentForm.consultRecordId = parseInt(event.data[0].cloudCustomData)
        _this.consultRecordId = _this.commentForm.consultRecordId
      }
      if (event.data[0].type === 'TIMImageElem'){
        if (event.data[0].from === String(_this.chatName)){
          _this.mList.push({time:time,message:event.data[0].payload.imageInfoArray[0].imageUrl,mine:'',type:'pic'})
          if (_this.msgsynchro === false){
            _this.mList2.push({time:time,message:'[图片]',mine:'',type:'text'}) //未触发同步消息时暂存在另一个数组中
          }
        }
      }
      else if (event.data[0].type === 'TIMTextElem'){//文本内容
        cvtMessage = event.data[0].payload.text

        console.log(_this.commentForm.consultRecordId)
        if (cvtMessage==='--结束咨询--' && event.data[0].cloudCustomData!==''){ //用户中止了，中止语暂定为--结束咨询--
          if (event.data[0].from === _this.chatName){
            _this.mList.push({time:time,message:cvtMessage,mine:'',type:'text'})

            clearInterval(_this.time);
            _this.consultStatus = "已结束"
            window.localStorage.removeItem('cons'+_this.chatName)
            console.log(_this.helpRecordId,_this.mentor)
            if (parseInt(_this.helpRecordId)!==0&&!isNaN(parseInt(_this.helpRecordId))){ //一并中断求助
              _this.$axios.post('http://106.14.247.163:8080/consultant/endHelp',
                  {helpRecordId:_this.helpRecordId,duration:Math.abs(Math.floor(Math.random()*10))})
              let message = _this.tim.createTextMessage({
                to: _this.mentor,
                conversationType: _this.TIM.TYPES.CONV_C2C,
                payload: {
                  text: '--求助完成--',
                },
              });
              _this.tim.sendMessage(message)
            }
            tim.setMessageRead({conversationID:'C2C'+_this.chatName})
            _this.$message.success('对方结束咨询')
            _this.dialogVisible2 = true
          }else{
            _this.$message.warning('用户'+event.data[0].from+'结束了咨询')
            tim.setMessageRead({conversationID:'C2C'+event.data[0].from})
            window.localStorage.removeItem('cons'+event.data[0].from)
          }

        }
        else{ //将消息显示到屏幕上
          if (event.data[0].from===_this.chatName){
            _this.mList.push({time:time,message:cvtMessage,mine:'',type:'text'})
            if (_this.msgsynchro === false){  //未触发同步消息时暂存在另一个数组中
              _this.mList2.push({time:time,message:cvtMessage,mine:'',type:'text'})
            }
          }
        }
      }else if (event.data[0].type === 'TIMCustomElem'){//定制内容，特指消息记录
        if(event.data[0].type === String(_this.chatName)){
          _this.mList.push({time:time,message:event.data[0].payload.data,mine:'',type:'history'})
          if (_this.msgsynchro === false){
            _this.mList2.push({time:time,message:'[消息记录]',mine:'',type:'text'})
          }
        }
      }
      else{
        if (event.data[0].from === _this.chatName) {
          _this.mList.push({time:time,message: event.data[0].payload.url, mine: '',type:'sound'})
          if (_this.msgsynchro === false){
            _this.mList2.push({time:time,message:'[语音]',mine:'',type:'text'})
          }
        }
      }
      _this.below()
      // 同步转发操作
      console.log('syncchro is :' + _this.synchro)
      if(_this.msgsynchro === true){
        let m = ''
        if (event.data[0].type === 'TIMImageElem'){ //图片类型只转发一条文字提示消息
          m = '[图片]'
        }
        else if (event.data[0].type === 'TIMTextElem'){ //文字类型转发带有标识符的消息，标识符将决定消息显示在主屏还是分屏上
          m = event.data[0].payload.text
        }else if (event.data[0].type==='TIMCustomElem'){
          m = '[消息记录]'
        }else{
          m = '[语音]'
        }
        console.log('mentor is '+_this.mentor)
        let message = tim.createTextMessage({
          to: _this.mentor,
          conversationType: TIM.TYPES.CONV_C2C,
          payload: {
            text: m,
          },
          cloudCustomData:'user'
        });
        console.log(message)
        let promise = tim.sendMessage(message)
        promise
            .then(function (imResponse) {
              // 发送成功
              console.log("repost success")
            })
            .catch(function (imError) {
              // 发送失败
              console.warn("sendMessage error:", imError);
            });
      }


      // event.data - 存储 Message 对象的数组 - [Message]
    };
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);


  },
  mounted() {

  },
  destroyed() {
    // 离开页面退出当前账号
    let promise = this.tim.logout();
    // promise
    //   .then(function (imResponse) {
    //     console.log(imResponse.data);
    //   })
    //   .catch(function (imError) {
    //     console.warn("logout error:", imError);
    //   });
  },
}
</script>

<style scoped>

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .name{
    font-family: "Microsoft YaHei",sans-serif;
    font-size: 20px;
    font-weight: bold;
  }
  .digit2 {
    font-family: "Microsoft YaHei",sans-serif;
    font-weight: bold;
    color: white;
    font-size: 48px;
    line-height:2.0;
  }
  .title1 {
    font-family: "PingFang SC",sans-serif;
    font-size: 16px;
    color: #000000;
    font-weight: normal;
    padding-top: 5px;
    padding-bottom: 0px;
  }
  .title2 {
    font-family: "PingFang SC",sans-serif;
    font-size: 16px;
    color: white;
    line-height: 1.0;
    font-weight: normal;
  }
  .message-area{
    background-color: #ffffee;
    height: 300px;
    border: 5px #cccccc;

  }
  .el-table{
    --el-table-border: 0px;
    --el-table-row-hover-background-color: none;
  }


</style>

<style scoped lang="scss">
.el-table__row>td{
  border: none;
}
@mixin toCla {
  color: #a5b5c1;
  font-size: 12px;
}
@mixin toClb {
  display: inline-block;
  > div:nth-child(1):before {
    content: "";
    width: 0px;
    height: 0px;
    border-top: 7px solid transparent;
    border-bottom: 7px solid transparent;

    position: absolute;
    top: 10px;
    font-size: 7px;
  }
  > div:nth-child(2) {
    color: #a5b5c1;
    font-size: 12px;
    margin-top: 9px;
  }
  > div:nth-child(1) {
    outline: none;
    font-size: 14px;
    position: relative;
    max-width: 350px;
    word-wrap: break-word;
    word-break: break-all;
    background: #fff;
    border-radius: 5px;
    display: inline-block;
    padding: 10px;
    -webkit-box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.1);
    box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;
  }
}
.box {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  margin-top: 2%;
  display: flex;
  // -moz-box-shadow: 2px 2px 5px #333333;
  // -webkit-box-shadow: 2px 2px 5px #333333;
  //box-shadow: 1px 1px 1px #333333;
  border: 1px solid #3d3d3d;
  position: relative;
  .t_left {
    width: 260px;
    height: 600px;
    overflow: auto;
    border-right: 1px solid #e5e5e5;
    .seek {
      overflow: hidden;
      background: red;
      position: absolute;
      width: 256px;
      z-index: 9;
      top: 0;
      left: 0;
    }
    .t_left_bot {
      // padding-top: 36px;
      overflow: auto;
      background: #3d3d3d;
      > div {
        width: 100%;
        height: 80px;
        background: #3333;
        border-bottom: 1px solid #e5e5e5;
        cursor: pointer;
        position: relative;
        div:nth-child(5) {
          position: absolute;
          width: 18px;
          height: 18px;
          line-height: 18px;
          text-align: center;
          font-size: 11px;
          top: 4px;
          left: 58px;
          color: #fff;
          background: red;
          border-radius: 50%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        div:nth-child(4) {
          position: absolute;
          width: 80px;
          font-size: 14px;
          top: 15px;
          left: 169px;
          color: #999;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          text-align: right;
        }
        div:nth-child(3) {
          position: absolute;
          width: 163px;
          font-size: 14px;
          top: 45px;
          left: 83px;
          color: #999;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        div:nth-child(2) {
          position: absolute;
          width: 90px;
          font-size: 16px;
          top: 13px;
          left: 83px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          color: #ffffff;
        }
        img {
          width: 60px;
          height: 60px;
          position: absolute;
          top: 10px;
          left: 10px;
          border-radius: 2px;
        }
      }
    }
  }
  .t_right {
    flex: 1;
    background: #ffffff;

    .t_right_bot {
      border-top: 1px solid #e5e5e5;
      height: 139px;
      width: 750px;
      background: #fff;
      position: relative;
      ::v-deep .t_limit {
        position: absolute;
        right: 93px;
        bottom: 17px;
        color: #b2b2b2;
      }
      ::v-deep textarea {
        resize: none;
        height: 100px;
        border: 0;
        width: 96%;
        display: block;
        margin: 0 auto;
        outline: none;
      }
      .r_i {
        position: absolute;
        right: 12px;
        bottom: 7px;
        color: #fff;
      }
      > div:nth-child(1) {
        display: flex;
        align-items: center;
        .icture_a {
          display: inline-block;
          cursor: pointer;
          position: relative;
          margin-left: 5px;

          ::v-deep .el-popover {
            width: 400px !important;
            height: 160px !important;
            overflow: auto !important;
          }
        }
        .icture {
          width: 30px;
          height: 30px;
          display: inline-block;
          margin: 4px 15px;
          cursor: pointer;
          overflow: hidden;
          position: relative;
        }
        input[type="file"] {
          color: transparent;
        }
        input {
          cursor: pointer !important;
          position: absolute;
          top: 0;
          left: 0;
          width: 30px;
          height: 30px;
          opacity: 0;
        }
        ::v-deep i {
          font-size: 27px;
        }
      }
    }
    .t_right_con {
      height: 410px;
      overflow: auto;
      .t_r_nmore {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        justify-content: center;
        font-size: 13px;
        color: #a5b5c1;
        background: 0 0;
        padding-left: 0;
        padding-right: 0;
        cursor: pointer;
      }
      .t_r_more {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        justify-content: center;
        font-size: 13px;
        color: #409eff;
        background: 0 0;
        padding-left: 0;
        padding-right: 0;
        cursor: pointer;
      }
    }

    .t_right_top {
      padding: 0 20px;
      color: #1c2438;
      font-size: 18px;
      font-weight: bold;
      line-height: 50px;
      text-shadow: #76828c 0 0 0.1em;
    }
    .hList-left {
      width: 100%;
      position: relative;
      overflow: auto;
      .hlAva {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        display: block;
        display: inline-block;
        margin: 10px 20px;
        vertical-align: top;
      }
      .hList-left-b {
        text-align: right;
        > div:nth-child(2) {
          @include toCla;
        }
        > div:nth-child(1) {
          @include toClb;
          > div:nth-child(1):before {
            border-top: 7px solid transparent !important;
            border-bottom: 7px solid transparent !important;
            border-left: 7px solid #fff !important;
            right: -7px !important;
          }
        }
      }
      .hList-left-a {
        > div:nth-child(3) {
          @include toCla;
        }
        > div:nth-child(2) {
          @include toClb;
          > div:nth-child(1):before {
            left: -7px !important;
            border-right: 7px solid #fff !important;
          }
        }
      }
    }
  }
  .active {
    transition: 300ms;
    background: #d6d6d6 !important;
  }
}

/* 设置滚动条的样式 */
::-webkit-scrollbar {
  width: 3px;
  height: 3px;
}

/* 滚动槽 */
::-webkit-scrollbar-track {
  border-radius: 10px;
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.1);
}
</style>